import axios from 'axios';
import readFileFormatBase64 from '../util/readFileFormatBase64';
import { isOffLine } from '../util/isOffLine';
import request from '../util/requset';

/**
 * 上传图片
 * @param {*} file 文件
 * @param {*} url 上传图片地址
 * @returns 'public/年/月-日/随机数.文件名'
 */
const uploadFile = (file, url) => {
  return new Promise((resolve, reject) => {
    const formData = new FormData();
    formData.append('file', file);
    axios
      .post(`${import.meta.env.VITE_BASE_API}${url}`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then((res) => {
        if (res.data) {
          resolve(res.data);
        } else {
          reject('error');
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
};

/**
 * 上传图片接口
 * @param {*} file 文件-必传
 * @param {*} url 上传地址，图片为base64时非必传
 * @returns
 */
export const uploadFileApi = async (file, url = '/upload/img') => {
  return isOffLine()
    ? await readFileFormatBase64(file)
    : await uploadFile(file, url);
};


/**
 * 大文件切片上传
 * 
 */
export const uploadChunkApi = async (data , fn) => {
  return new Promise((resolve, reject) => {
    axios
      .post(`${import.meta.env.VITE_BASE_API}/upload/chunk`, data, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress:fn
      })
      .then((res) => {
        if (res.data) {
          resolve(res.data);
        } else {
          reject('error');
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
}

// 检测文件是否存在
export const verifyFileApi = async (data) => {
  return request('/chunk/verify',{method:'POST',data})
}

// 合并文件请求
export const mergeFileApi = async (data) => {
  return request('/chunk/merge',{method:'POST',data});
}